<template>
  <SwModal :isShow.sync="isShowUploadingPayment" :isShowBg="true" :isShowCloseBtn = "true" :okText="''" :isCloseOnClickBg="true">
    <div class="uploadPayImgBox" ref="uploadPayImgBox">
      <h3 class="title">{{lang['uploading payment voucher']}}</h3>
      <p class="tip">{{lang['confirm that payment completed']}}</p>
      <ul class="waitUploadImgList">
        <li v-for="(item, index) in uploadedImgs">
          <img :src="item.Img" class="waitUploadImg">
        </li>
        <li v-for="(item, index) in waitUploadImgs">
          <img :src="item.src" class="waitUploadImg">
          <a class="del" @click="delWaitUploadImg(index)"></a>
        </li>
        <li>
          <label class="file" @click="focusLastFileInput">
            <img src="./../images/uploadingImgBox.png">
            <span>{{lang['Click to upload a picture']}}</span>
          </label>
        </li>
        <!-- <div class="addImgUpload">
          <p class="file">
            <img src="./../images/uploadingAdd.png"><br/>
            <span>继续上传</span>
          </p>
        </div> -->
      </ul>
      <button type="button" class="subtimBox blue" @click="submitUpload">{{lang['determineBth']}}</button>
    </div>
 </SwModal>
</template>

<script>
import SwModal from '@/components/SwModal'
import Utils from '@/utils/Utils.js'
import ModalApi from '@/components/SwModal/api.js'
import $ from 'jquery'
import EventBus from '@/service/EventBus.js'

export default {
  props: [
    'lang',
    'propIsShowUploadingPayment',
    'currentOrderItem'
  ],
  watch: {
    isShowUploadingPayment (nv) {
      this.$emit('update:propIsShowUploadingPayment', nv)
    },
    propIsShowUploadingPayment (nv) {
      this.isShowUploadingPayment = nv
      if (nv === true) this.init()
    }
  },
  data () {
    return {
      isShowUploadingPayment: false,
      waitUploadImgs: [],
      waitUploadImgInputs: [],
      uploadedImgs: [],
      payInfoId: '',
      $uploadPayImgBox: null,
      $waitUploadInputs: null
    }
  },
  components: {
    SwModal
  },
  methods: {
    /*
    每次点上传之前都会自动生成一个file input，然后使它click()
    */

    // 生成新的intile
    appendFileInput () {
      let $input = $('<input type="file" class="waitUploadImgInput" accept="image/gif,image/jpeg,image/jpg,image/png">')
      this.$uploadPayImgBox.append($input)
      this.$waitUploadInputs = $('.waitUploadImgInput')
    },
    // 使最新的file input自动打开选择文件窗口
    focusLastFileInput () {
      // 因为每点一次就会添加一次change事件，所以每次添加前都要移除
      this.$waitUploadInputs.last().off('change', this.selectImg).on('change', this.selectImg).click()
    },
    removeFileInputByIndex (index) {
      this.$waitUploadInputs.last().off('change')
      .end().eq(index).remove()
      this.$waitUploadInputs = $('.waitUploadImgInput') // 删除完一个元素后，这个变量也要改
    },
    removeAllFileInput () {
      this.$waitUploadInputs && this.$waitUploadInputs.remove()
    },
    getImgBase64 (fileNode) {
      let files = fileNode.files
      let promise = Utils.makePromise()
      let size = files[0].size / 1024
      let reader = new FileReader()
      reader.readAsDataURL(files[0])
      reader.onload = function (e) {
        if (size > 5000) {
          promise.rejectHandle()
        } else {
          promise.resolveHandle(this.result)
        }
      }
      return promise
    },
    selectImg () {
      this.getImgBase64(this.$waitUploadInputs.last()[0])
      .then((res) => {
        this.waitUploadImgs.push({
          src: res
        })
        // 保证永远有一个待上传的file input
        this.appendFileInput()
      })
      .catch(() => {
        this.$waitUploadInputs.last().off('change')  // 添加大于5M图片 也会绑定一次事件，第二次添加小于5M的图片，会触发两次
        ModalApi.message(this.lang['the uploaded pictures cant be larger than'])  // '上传的图片不能大于5M！'  this.lang['the uploaded pictures can't be larger than']
      })
    },
    delWaitUploadImg (index) {
      this.waitUploadImgs.splice(index, 1)
      this.removeFileInputByIndex(index)
    },
    submitUpload () {
      if (this.waitUploadImgs.length < 1) {
        ModalApi.message(this.lang['please upload the picture'])  // '请上传图片！'
        return
      }

      let formData = new FormData()
      this.$waitUploadInputs.each(function (index) {
        this.files[0] && formData.append('AppealImg' + index, this.files[0])
      })
      formData.append('orderDetailID', this.currentOrderItem.ID)
      formData.append('payInfoId', this.payInfoId)
      this.$host2.post('Appeal/BuyerUploadPayCertificate', formData, {
        config: {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        },
        isShowLoading: true
      }).then((res) => {
        setTimeout(() => {
          EventBus.$emit('refreshUnfilledOrderList')
        }, 1000)
        ModalApi.message(this.lang['upload Success'])  // '上传成功'
        this.isShowUploadingPayment = false
      })
    },
    getUploadedImgs () {
      this.$host2.post('Appeal/GetOrderPayCertInfo', {
        detailID: this.currentOrderItem.ID
      }, {
        ignorableCodes: '51077'
      }).then((res) => {
        if (res.Data && res.Data.Imgs && res.Data.Imgs.length) {
          this.uploadedImgs = res.Data.Imgs
          this.payInfoId = res.Data.ID
        }
      })
    },
    reset () {
      this.waitUploadImgs = []
      this.waitUploadImgInputs = []
      this.uploadedImgs = []
      this.payInfoId = ''
      this.removeAllFileInput()
    },
    init () {
      this.reset()
      this.appendFileInput()
      this.getUploadedImgs()
    }
  },
  mounted () {
    this.$uploadPayImgBox = $(this.$refs.uploadPayImgBox)
  }
}
</script>

<style lang="less">
@import './../css/common.less';

.modal {

  .uploadPayImgBox {
    width: 830px;
    padding: 10px 40px 20px;
    border-radius: 8px;
    font-weight: 300;

    .title {
      font-size: 14px;
      color: #fff;
    }

    .tip {
      padding-bottom: 10px;
      line-height: 20px;
      color: #fff;
      border-bottom: solid 1px #3b3e46;
      font-size: 12px;
    }
    .addImgUpload {
      float: left;
      margin: 40px 30px 0 0;
      width: 170px;
      height: 170px;
      line-height: 170px;
      border:dashed 1px #979797;

      p {
        display: inline-block;
        line-height: 20px;
        width: 100%;
        text-align: center;
        vertical-align: middle;
      }
    }
    .waitUploadImgList {
      overflow: auto;
      padding-bottom: 20px;
      max-height: 420px;
      min-height: 220px;

      li {
        position: relative;
        float: left;
        margin: 40px 30px 0 0;
        width: 170px;
        height: 170px;
        font-size: 12px;

        &:last-child{
          border: dashed 1px #ddd;
        }

        .waitUploadImg {
          width: 100%;
          height: 100%;
        }

        .del {
          background: url(../images/delete2.png);
          position: absolute;
          top: 4px;
          right: 4px;
          width: 18px;
          height: 18px;
        }
      }
      .file {
        display: inline-block;
        line-height: 20px;
        width: 100%;
        height: 100%;
        text-align: center;
        vertical-align: middle;
        color: #fff;

        img {
          margin: 50px auto 10px;
          display: block;
          width: 28px;
        }
      }
    }

    .waitUploadImgInput {
      display: none;
    }

    .subtimBox {
      display: block;
      margin: 0 auto;
      width:220px;
      height: 40px;
      line-height: 40px;
      color: #fff;
      text-align: center;
      border-radius: 5px;

      &.red {
        background: @red;
      }

      &.blue {
        background: @blue;
      }
    }
  }
}
</style>
